package com.jiumi.common.utils;

import com.jiumi.common.core.domain.AjaxResult;
import com.jiumi.common.core.redis.RedisCache;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.concurrent.TimeUnit;


/**
 * @author小象智慧卧龙在此
 * @date 2020/10/9 14:45
 */
public class SMSCode {

    public static final String firstWatchapproveMsg1="【木棉中国】您的看房奖励红包已到您的木棉APP账户。更多房源信息请您登录木棉APP，查看详情。";



    public static AjaxResult sunHaosendSMS(RedisCache redisCache, String phone, String temlate)throws Exception {
        AjaxResult ajaxResult=AjaxResult.success();
        Integer code = (int) ((Math.random() * 9 + 1) * 100000);//生成6位随机数
        String postData = "uid=13416&pw=A3E7D3A3&mb="+phone+"&ms="+ URLEncoder.encode("【"+temlate+"】验证码为："+code+",您正在进行登录校验，切勿将验证码泄露于他人，验证码10分钟内有效。","utf-8");

        String postUrl="http://59.110.24.249:8090/send.do";

        try {

            /*//发送POST请求
            URL url = new URL(postUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setUseCaches(false);
            conn.setDoOutput(true);
            conn.setRequestProperty("Content-Length", "" + postData.length());
            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            out.write(postData);
            out.flush();
            out.close();
            //获取响应状态
            if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
                ajaxResult=AjaxResult.error("连接失败");
                return ajaxResult;
            }
            //获取响应内容体
            String line, result = "";
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            while ((line = in.readLine()) != null) {
                result += line + "\n";
            }
            in.close();
            System.out.println("connect success!");*/
            String key = "phone_verify_code" + phone;
            redisCache.setCacheObject(key, code,600, TimeUnit.SECONDS);
            ajaxResult.put("phoneCode",code);
            return ajaxResult;
        } catch (Exception e) {
            e.printStackTrace(System.out);
            ajaxResult=AjaxResult.error(e.getMessage());
        }
        return ajaxResult;
    }


    public static AjaxResult sunHaosendNoticeSMS(String phone, String temlate)throws Exception {
        AjaxResult ajaxResult=AjaxResult.success();
        String postData = "uid=13416&pw=A3E7D3A3&mb="+phone+"&ms="+ URLEncoder.encode(temlate,"utf-8");

       // Integer code = (int) ((Math.random() * 9 + 1) * 100000);//生成6位随机数
        //String postData = "uid=13416&pw=A3E7D3A3&mb="+phone+"&ms="+java.net.URLEncoder.encode("【"+temlate+"】短信验证码为："+code+"。此验证码只用于验证，5分钟内有效","utf-8");


        String postUrl="http://59.110.24.249:8090/send.do";

        try {

            //发送POST请求
            URL url = new URL(postUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setUseCaches(false);
            conn.setDoOutput(true);
            conn.setRequestProperty("Content-Length", "" + postData.length());
            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            out.write(postData);
            out.flush();
            out.close();
            //获取响应状态
            if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
                ajaxResult=AjaxResult.error("连接失败");
                return ajaxResult;
            }
            //获取响应内容体
            String line, result = "";
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            while ((line = in.readLine()) != null) {
                result += line + "\n";
            }
            in.close();
            return ajaxResult;
        } catch (IOException e) {
            ajaxResult=AjaxResult.error(e.getMessage());
        }
        return ajaxResult;
    }

    public static AjaxResult sendSms(RedisCache redisCache, String phone) throws Exception {
        AjaxResult ajaxResult=AjaxResult.success();
        try{
            HttpClient httpClient = new HttpClient();
            PostMethod postMethod = new PostMethod("http://api.1cloudsp.com/api/v2/single_send");
            postMethod.getParams().setContentCharset("UTF-8");
            postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler());

            String accesskey = "xx"; //用户开发key
            String accessSecret = "xx"; //用户开发秘钥
            Integer code = (int) ((Math.random() * 9 + 1) * 100000);//生成6位随机数
            NameValuePair[] data = {
                    new NameValuePair("accesskey", accesskey),
                    new NameValuePair("secret", accessSecret),
                    new NameValuePair("sign", "139484"),
                    new NameValuePair("templateId", "167902"),
                    new NameValuePair("mobile", phone),
                    new NameValuePair("content", URLEncoder.encode(code+"", "utf-8"))//（示例模板：{1}您好，您的订单于{2}已通过{3}发货，运单号{4}）
            };
            postMethod.setRequestBody(data);
            postMethod.setRequestHeader("Connection", "close");
            int statusCode = httpClient.executeMethod(postMethod);
//            System.out.println("statusCode: " + statusCode + ", body: "
//                    + postMethod.getResponseBodyAsString());
            String key = "phone_verify_code" + phone;
            redisCache.setCacheObject(key, code,300, TimeUnit.SECONDS);
            //ajaxResult.put("phoneCode",code);
            return ajaxResult;
        }
        catch (IOException e) {
//            e.printStackTrace(System.out);
            ajaxResult=AjaxResult.error(e.getMessage());
        }

        return ajaxResult;
    }



}
